<template>
  <el-dialog
    :visible="isShow"
    :title="mode === 'add' ? '新增角色' : '编辑角色'"
    width="500px"
    @close="closeEvent"
  >
    <el-form ref="form" label-width="100px" :model="form" :rules="rules">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model.trim="form.name" />
      </el-form-item>
      <el-form-item
        label="角色描述"
        prop="description"
      ><el-input v-model.trim="form.description" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <el-button @click="closeEvent">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { sysRolePost, sysRolePut } from '@/api/setting.js'
export default {
  model: {
    prop: 'isShow'
  },
  props: {
    isShow: {
      type: Boolean,
      default: false
    },
    list: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      mode: 'add',
      form: {
        name: '',
        description: ''
      },

      initForm: '',
      rules: {
        name: [
          {
            required: true,
            message: '必填',
            trigger: 'change'
          },
          {
            validator: (rule, value, callback) => {
              let result = ''
              if (this.mode === 'add') {
                result = this.list.some((item) => {
                  return item.name === value
                })
              } else {
                result = this.list.some((item) => {
                  return item.name === value && item.id !== this.form.id
                })
              }

              result ? callback(new Error('请不要重名')) : callback()
            }
          }
        ],
        descrption: [
          {
            required: true,
            message: '必填',
            trigger: 'change'
          }
        ]
      }
    }
  },
  created() {},
  methods: {
    closeEvent() {
      this.$emit('update:isShow', false)
      this.$refs.form.resetFields()

      this.form = {
        name: '',
        description: ''
      }
    },
    submit() {
      this.$refs.form.validate(async(result) => {
        if (result) {
          // 调用api
          if (this.mode === 'add') {
            // console.log(result)
            await sysRolePost(this.form)
            // 刷新父级列表数据
            this.$emit('currChange', 1)
          } else {
            await sysRolePut(this.form)
          }
          this.$message.success(this.mode === 'add' ? '添加成功' : '编辑成功')
          // 关闭弹窗
          this.closeEvent()
          this.$emit('getData')
          // console.log(result)
        }
      })
    }
  }
}
</script>

<style></style>
